//
//  SQLiteManager.m
//  LittleSummary
//
//  Created by 郝旭珊 on 2018/1/20.
//  Copyright © 2018年 郝旭珊. All rights reserved.
//

#import "SQLiteManager.h"
#import <sqlite3.h>

/// 全局数据库操作句柄
static sqlite3 *_db;    //sqlite数据库 _db

@implementation SQLiteManager

#pragma mark - 初始化
+ (instancetype) sharedManager{
    static SQLiteManager *instance;
    static dispatch_once_t onceToken ;
    dispatch_once(&onceToken, ^{
        instance = [[super allocWithZone:NULL] init] ;
    });
    return instance;
}


+ (id) allocWithZone:(struct _NSZone *)zone{
    return [SQLiteManager sharedManager];
}


- (id) copyWithZone:(struct _NSZone *)zone{
    return [SQLiteManager sharedManager];
}


#pragma mark - 接口
/**
 * 打开数据库, 如果没有就创建
 */
- (void)openDB:(NSString *)dbName{
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    NSString *filePath = [documentPath stringByAppendingPathComponent:dbName];
    NSLog(@"%@",filePath);
    //将OC字符串 -> C语言字符串
    const char *cfilePath = filePath.UTF8String;
    /*
     filename: 数据库的全路径
     ppDb: 句柄, 指针,对数据库的所有操作都基于此句柄
     返回值:  int == SQLITE_OK 成功
     */

    if (sqlite3_open(cfilePath,&_db) != SQLITE_OK){
        NSLog(@"失败");
        return;
    }

    [self creatTable];
    [self insertSql];
}


- (BOOL)exeSQL:(NSString *)sql{

    //  const char *sql
    const char *cSql = sql.UTF8String;
    return sqlite3_exec(_db, cSql, nil, nil, nil);
}


- (void)creatTable{
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"db.sql" ofType:nil];
    NSString *sql = [NSString stringWithContentsOfFile:filePath usedEncoding:nil error:nil];
    [self exeSQL:sql];

    NSLog(@"%@",sql);
}


- (void)insertSql{
    NSString *sql = @"INSERT INTO T_Goods (id,name,price,description,number) VALUES (0,'牙膏',3,'要地方大幅度的',1);";
    if ([self exeSQL:sql]){
        NSLog(@"插入成功");
    }else{
        NSLog(@"插入失败");
    }
}


- (void)deleteSql{

}



@end
